package com.atguigu.flink.chapter07.watermark;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/7/7 10:23
 */
public class Flink02_Window_Tumbling_1 {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        env.getConfig().setAutoWatermarkInterval(2000);
        
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                System.out.println("xxxxx");
                return new WaterSensor(
                    data[0],
                    Long.valueOf(data[1]),
                    Integer.valueOf(data[2])
                );
            })
            .assignTimestampsAndWatermarks(
                new WatermarkStrategy<WaterSensor>() {
                    @Override
                    public WatermarkGenerator<WaterSensor> createWatermarkGenerator(
                       WatermarkGeneratorSupplier.Context context) {
                        return new MyWMS();
                    }
                }
                .withTimestampAssigner((ws, ts) -> ws.getTs())
            )
            .keyBy(WaterSensor::getId)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                // 当时间超过了窗口的结束时间的时候, 会自动触发计算. 方法会执行
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<WaterSensor> elements,  // 存储了这窗口内所有的元素
                                    Collector<String> out) throws Exception {
                    List<WaterSensor> list = new ArrayList<>();
                    for (WaterSensor element : elements) {
                        list.add(element);
                    }
                    out.collect(key + " " + new Date(ctx.window().getStart()) + " " + new Date(ctx.window().getEnd()) + "  " + list);
                    
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    static class  MyWMS implements WatermarkGenerator<WaterSensor> {
        
        private long maxTs = Long.MIN_VALUE + 3000 + 1;
    
        @Override
        public void onEvent(WaterSensor event,
                            long eventTimestamp,
                            WatermarkOutput output) {
            System.out.println("MyWMS.onEvent");
    
            maxTs = Math.max(maxTs, eventTimestamp);
            // 间歇性发射水印
            output.emitWatermark(new Watermark(maxTs - 3000 - 1));
        }
    
        // 周期性水印
        @Override
        public void onPeriodicEmit(WatermarkOutput output) {
            //            System.out.println("MyWMS.onPeriodicEmit");
            //            output.emitWatermark(new Watermark(maxTs - 3000 - 1));
            
        }
    }
}
